//
//  LROAuthViewController.swift
//  LRWeibo
//
//  Created by 雷路荣 on 15/12/18.
//  Copyright © 2015年 leilurong. All rights reserved.
//

import UIKit

import SVProgressHUD

class LROAuthViewController: UIViewController, UIWebViewDelegate {//遵守代理协议
    //懒加载webView
    private lazy var webView = UIWebView()
    // 在这赋值的话,不需要添加约束,系统会自动添加约束
    override func loadView() {
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "dismiss")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Done, target: self, action: "autoFill")
        let url = LRNetworkTool.sharedNetworkTool.oAuthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)

    }
    //MARK - 填充账号密码
    func autoFill() {
        // 创建js代码
        let js = "document.getElementById('userId').value='czbkiosweibo@163.com'; document.getElementById('passwd').value='czbkios007';"
        // 让webView来执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //MARK - 取消 这里加private修饰后必须加@objc彩不会奔掉
    @objc private func dismiss(){
        //关闭指示器
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK - UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
        // 显示正在加载
        // showWithStatus会一直显示
        // showInfoWithStatus,过1s自动关闭
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // webView是否要去加载一个网址,返回true去加载, false不去加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL?.absoluteString
        print("\(url)")
        // 只有点击 取消或授权,才会加载 授权回调地址,其他情况不会加载授权回调地址
        // 如果不是授权回调地址,直接加载
        if !url!.hasPrefix(LRNetworkTool.sharedNetworkTool.redirect_uri) {
            return true
        }
        //来到这里说明是授权回调地址，判断是点击了取消还是授权按钮
        //点击取消的打印，会以error_uri=开头 http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        //点击授权的打印，会以code=开头 http://www.baidu.com/?code=f6fbb61940dce6776866429e7830a75d
        // 获取url中?后面的内容: URL.query就是问号后面的东西
        if let query = request.URL?.query {
            // 能到这里面来,表示query有值
            let codeString = "code="
            // 判断query是否以code=开头
            if query.hasPrefix(codeString) {//说明点击了授权
                // Stirng和NSString之间的转换是不需要添加as? 或 as! 直接使用as
                let queryNSString = query as NSString
                let code = queryNSString.substringFromIndex(codeString.characters.count)
                print("code = \(code)")
                loadAccessToken(code)
            }else{//说明点击了取消
                dismiss()
            }
        }else{
            print("query没有值")
        }
        return false
    }
    //MARK - 控制器加载AccessToken
    func loadAccessToken(code:String) {
        LRNetworkTool.sharedNetworkTool.loadAccessToken(code) { (result, error) -> () in
            // 判断网络请求是否有错误
            if error != nil && result == nil {
                print("eror:\(error)")
                SVProgressHUD.showErrorWithStatus("你的网络不给力！")
                //1秒后关闭
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.dismiss()
                })
                return
            }
            // 能到下面来没有错误,获取到了AccessToken
            print("获取到了AccessToken:\(result)")
            //实例化对象，字典转模型
            let userAccount = LRUserAccount(dict: result!)
            //保存
            userAccount.saveUserAccount()
            print("保存userAccount=\(userAccount)")
            //切换到欢迎界面
            //(UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
            AppDelegate.outSwitchRootViewController(false)
            // 13.关闭登录界面
            self.dismiss()
        }
    }
}


























